﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Windows;
using System.Windows.Forms;
using MessageBox = System.Windows.MessageBox;
using OpenFileDialog = Microsoft.Win32.OpenFileDialog;

namespace ImageConverter {
  /// <summary>
  /// MainWindow.xaml 的交互逻辑
  /// </summary>
  public partial class MainWindow: Window {
    public MainWindow() {
      InitializeComponent();
    }
    /// <summary>
    /// 选择的图片文件
    /// </summary>
    private List<string> SelectedImages { get; set; }
    private List<string> SelectedImageNames { get; set; }

    private List<string> SelectImage() {
      OpenFileDialog ofd = new OpenFileDialog();
      ofd.Title = "选择图片文件";
      ofd.Multiselect = true;
      ofd.Filter = "图片文件(Jpeg, Gif, Bmp, 等)|*.jpg;*.jpeg;*.gif;*.bmp;*.tif; *.tiff; *.png|Jpeg 文件 (*.jpg;*.jpeg)|*.jpg;*.jpeg |GIF 文件 (*.gif)|*.gif |BMP 文件 (*.bmp)|*.bmp|Tiff 文件 (*.tif;*.tiff)|*.tif;*.tiff|Png 文件 (*.png)| *.png | 所有文件(*.*)|*.*";
      ofd.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyPictures);


      var ok = ofd.ShowDialog();

      if(!ok.HasValue || !ok.Value) {
        return null;
      }

      return ofd.FileNames.ToList();
    }

    // 选择图片
    private void SelectedImage_OnClick(object sender, RoutedEventArgs e) {
      SelectedImages = SelectImage();

      if(SelectedImages == null) return;

      var list = new List<string>();
      foreach(string img in SelectedImages) {
        list.Add(Path.GetFileName(img));
      }

      SelectedImageNames = list;

      ImageList.ItemsSource = SelectedImageNames;
    }
    // 保存图片
    private void SaveImage_OnClick(object sender, RoutedEventArgs e) {
      // 判断是否有图片
      if(SelectedImages == null || SelectedImages.Count == 0) {
        MessageBox.Show("未选择图片，不能进行转换");
        return;
      }

      // 判断是否选择格式
      string format;
      try {
        format = SelectedFormat.SelectedItem.ToString();
        // 如果获取到的值带有命名空间，则只获取非命名空间的部分
        if(format.Contains(":")) {
          format = format.Split(new[] { ":" }, StringSplitOptions.RemoveEmptyEntries)[1];
        }
      } catch {
        MessageBox.Show("未选择格式");
        return;
      }
      // 获取路径并判断是否为空
      string dir = SelectSaveFilePath();
      if(string.IsNullOrEmpty(dir)) {
        MessageBox.Show("未选择文件路径，保存失败");
        return;
      }
      // 是否需要灰度化
      var isChecked = ToGray.IsChecked;
      var isToGray = isChecked.HasValue && isChecked.Value;

      foreach(string img in SelectedImages) {
        switch(format) {
          case ".bmp":
            Save(img, dir, ImageFormat.Bmp, isToGray);
            break;
          case ".gif":
            Save(img, dir, ImageFormat.Gif, isToGray);
            break;
          case ".jpg":
            Save(img, dir, ImageFormat.Jpeg, isToGray);
            break;
          case ".png":
            Save(img, dir, ImageFormat.Png, isToGray);
            break;
          case ".tif":
            Save(img, dir, ImageFormat.Tiff, isToGray);
            break;
          case ".wmf":
            Save(img, dir, ImageFormat.Wmf, isToGray);
            break;
          case ".exif":
            Save(img, dir, ImageFormat.Exif, isToGray);
            break;
          case ".emf":
            Save(img, dir, ImageFormat.Emf, isToGray);
            break;
          case ".icon":
            Save(img, dir, ImageFormat.Icon, isToGray);
            break;
          case ".memorybmp":
            Save(img, dir, ImageFormat.MemoryBmp, isToGray);
            break;

        }
      }

      MessageBox.Show("转换成功！");
      ImageList.ItemsSource = null;

    }
    /// <summary>
    /// 选择保存文件路径
    /// </summary>
    /// <returns>选择的目录路径</returns>
    private static string SelectSaveFilePath() {
      FolderBrowserDialog fbd = new FolderBrowserDialog {
        RootFolder = Environment.SpecialFolder.Desktop,
        ShowNewFolderButton = true
      };
      var r = fbd.ShowDialog();

      // 如果没有点击   确定   或者  是  ，则返回   null
      if(r != System.Windows.Forms.DialogResult.OK && r != System.Windows.Forms.DialogResult.Yes) {
        return null;
      }

      return fbd.SelectedPath;
    }

    /// <summary>
    /// 保存图像文件
    /// </summary>
    /// <param name="sourceImage">源文件</param>
    /// <param name="targetImage">目标文件</param>
    /// <param name="format">目标文件格式</param>
    /// <param name="isToGray">是否需要灰度化</param>
    private void Save(string sourceImage, string targetImage, ImageFormat format, bool isToGray = false) {
      var name = Path.GetFileNameWithoutExtension(sourceImage);
      var f = format.ToString().ToLower();
      targetImage = Path.Combine(targetImage, $"{name}.{f}");

      // 灰度化
      var b = isToGray ? new Bitmap(sourceImage).ToGray() : new Bitmap(sourceImage);

      var img = new PictureBox { Image = b };
      img.Image.Save(targetImage, format);
    }


    private void MainWindow_OnLoaded(object sender, RoutedEventArgs e) {
      var format = new[] {
        ".bmp",
        ".gif",
        ".jpg",
        ".png",
        ".tif",
        ".wmf",
        ".exif",
        ".icon",
        ".emf"
      };

      SelectedFormat.ItemsSource = format;
      SelectedFormat.Text = ".jpg";
    }

  }
}
